package lt.vu.spf.graph;

import java.io.Serializable;

/**
 * @author Mantas Sinkevičius
 */
public class Edge implements Serializable {
    private static final long serialVersionUID = 4095817491683347660L;

    private Vertex v1;
    private Vertex v2;
    private float weight;
    private boolean inShortestPath;

    public Edge(Vertex v1, Vertex v2) {
        this.v1 = v1;
        this.v2 = v2;
        weight = calculateWeight();
    }

    /**
     * Suskaičiojamas briaunos svoris.
     * @return linijos ilgis pikseliais
     */
    private float calculateWeight() {
        return (float) Math.sqrt((v1.getX() - v2.getX()) * (v1.getX() - v2.getX()) + (v1.getY() - v2.getY())
                * (v1.getY() - v2.getY()));
    }

    /**
     * Suskaičiojamas vidurinysis briaunos taškas erdvėje.
     * @return viduriniojo briaunos taško koordinatės
     */
    public int[] getMidPoint() {
        float mx = (v1.getX() + v2.getX()) / 2;
        float my = (v1.getY() + v2.getY()) / 2;
        return new int[] { (int) mx, (int) my };
    }

    public Vertex getV1() {
        return v1;
    }

    public Vertex getV2() {
        return v2;
    }

    public float getWeight() {
        return weight;
    }

    public void setWeight(float weight) {
        if (weight <= 0) {
            // Neigiamas svoris Dijkstra algoritme nėra galimas.
            this.weight = 0;
            return;
        }
        this.weight = weight;
    }

    public boolean isInShortestPath() {
        return inShortestPath;
    }

    public void setInShortestPath(boolean inShortestPath) {
        this.inShortestPath = inShortestPath;
    }

    @Override
    public boolean equals(Object obj) {
        Edge edge = (Edge) obj;
        if (edge.getV1().equals(this.v1) && edge.getV2().equals(this.v2)) {
            return true;
        }
        if (edge.getV2().equals(this.v1) && edge.getV1().equals(this.v2)) {
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        return String.format("%.5g%n", weight);
    }

}
